package lib.bone.nepudata.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import lib.bone.access.constant.ResearchTypeConst;
import lib.bone.access.module.dict.DictServiceCtl;
import lib.bone.access.module.dict.entity.NepuTopicDict;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.PageResultDTO;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.exception.BusinessException;
import lib.bone.nepudata.dao.NepuTopicDAO;
import lib.bone.nepudata.domain.entity.NepuTopic;
import lib.bone.nepudata.expose.WorkloadService;
import lib.bone.nepudata.service.ResearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Author : cg
 * @Date : 2021-1-12
 * 未完成
 */
/**
 * cg 2022-4-6
 */

/**
 * 具体内容由@kindear 实现
 */
@Slf4j
@Service
@EnableAsync
public class NepuTopicServiceImpl implements ResearchService<NepuTopic,String> {
    @Autowired
    NepuTopicDAO nepuTopicDAO;

    @Autowired
    DictServiceCtl dictServiceCtl;

    @Autowired(required = false)
    WorkloadService workloadService;

    @Override
    public List<NepuTopic> getByIdIn(List<String> ids) {
        return nepuTopicDAO.findByIdIn(ids);
    }

    @Override
    public String getProjectCode(String s) {
        Optional<NepuTopic> entityOp = getById(s);
        if (entityOp.isPresent()){
            return entityOp.get().getTopicCode();
        }else {
            return "无";
        }
    }



    /**
     * 修复工作量记录
     */
    @Async("threadExecutor")
    @Transactional
    public void fixWorkload(NepuTopic topic){
        // 获取开始时间和结束时间
        Date startDate = topic.getStartDate();
        Date endDate = topic.getEndDate();
        //相差月份
        long betweenMonth = DateUtil.betweenMonth(startDate,endDate,false) + 1;
        // 获取词典信息
        Optional<Object> dictOp = dictServiceCtl.getById(topic.getTopicDictId(),ResearchTypeConst.TOPIC);
        if (!dictOp.isPresent()) {
//            log.info("{}对应词典不存在",topic.getTopicDictId());
            log.info("[{}]:工作量修复失败",topic.getTopicName());
            return;
        }
        NepuTopicDict dict = (NepuTopicDict) dictOp.get();
        double workload = dict.getWorkloadMax() * betweenMonth * 1.0 / 12;
        double oldLog = topic.getWorkload();
        // 更新对应记录
        topic.setWorkload(workload);
        this.updateOne(topic);
//        Optional<NepuWorkload> workloadOp = workloadService.getLinkEntity(topic.getId());
//        if (!workloadOp.isPresent()) throw new BusinessException(ResponseCodeConst.NOT_FOUND);
//        NepuWorkload workload1 = workloadOp.get();

//        workload1.setWorkload(workload);
        log.info("[{}]:原工作量:{},经修正后:{}",topic.getTopicName(),oldLog,workload);
    }


    public List<NepuTopic> getAll(){
        return nepuTopicDAO.findAll();
    }

    public List<NepuTopic> getAll(Example example){
        return nepuTopicDAO.findAll(example);
    }

    /**
     * 根据课题编码查询
     * @param topicCode
     * @return
     */
    //该方法有问题
    @Deprecated
    public Optional<NepuTopic> getByTopicCode(String topicCode){
        List<NepuTopic> topics = nepuTopicDAO.findByTopicCode(topicCode);
        if (topics.size()>0){
            return Optional.of(topics.get(0));
        }
        return Optional.empty();
    }

    public List<NepuTopic> getByTopicCodeAsList(String topicCode){
        List<NepuTopic> topics = nepuTopicDAO.findByTopicCode(topicCode);
        return topics;
    }

    public List<NepuTopic> getByTopicCodeV2(String topicCode){
        return nepuTopicDAO.findByTopicCode(topicCode);
    }

    @Override
    public String getServiceType() {
        return ResearchTypeConst.TOPIC;
    }

    @Override
    public NepuTopic saveOne(NepuTopic nepuTopic) {
        if (Validator.isNotEmpty(nepuTopic.getId())){
            throw new BusinessException(ResponseCodeConst.ERROR_PARAM);
        }
        return nepuTopicDAO.save(nepuTopic);     }

    @Override
    public NepuTopic updateOne(NepuTopic nepuTopic) {
        if (Validator.isEmpty(nepuTopic.getId())){
            throw new BusinessException(ResponseCodeConst.ERROR_PARAM);
        }
        return nepuTopicDAO.save(nepuTopic);
    }

    @Override
    public PageResultDTO<NepuTopic> getAll(Pageable pageable, Example<NepuTopic> example) {
        Page<NepuTopic> page;
        //是否为空 --
        if(Validator.isEmpty(example)){
            page = nepuTopicDAO.findAll(pageable);
        }else {
            page = nepuTopicDAO.findAll(example,pageable);
        }
        List<NepuTopic> list = page.getContent();
        PageResultDTO<NepuTopic> pageResultDTO = new PageResultDTO<>();
        pageResultDTO.setContent(list);
        pageResultDTO.setSize(page.getSize());
        pageResultDTO.setTotalPages(page.getTotalPages());
        pageResultDTO.setNumber(page.getNumber());
        pageResultDTO.setTotalElements(page.getTotalElements());

        return pageResultDTO;
//        return null;
    }

    @Override
    public ResponseDTO deleteById(String id) {
        Integer useCount = workloadService.countByLinkId(id);
        // Long useCount = nepuResearchWorkloadDAO.countByResearchTypeAndMapperId("教学科研获奖",id);
        if(useCount > 0){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"存在关联该奖励的科研工作量信息,拒绝执行删除!");
        }
        //判断数据是否存在
        Optional<NepuTopic> nepuTopicOp = getById(id);
        if(!nepuTopicOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"ID:["+id+"]对应数据不存在");
        nepuTopicDAO.deleteById(id);
        return ResponseDTO.succMsg("删除成功!");
    }
    @Override
    public Optional<NepuTopic> getById(String id) {
        return nepuTopicDAO.findById(id);
    }

    public void batchDelete(List<String> ids){
        nepuTopicDAO.deleteByIdIn(ids);
    }
//    @Override
//    public ResponseDTO apply(String id) {
//        NepuTopic nepuTopic = getById(id).get();
//        //更新状态为     1：申请
//        nepuTopic.setApplyStatus(ApplyStatus.APPLY_SUBMIT);
//        return ResponseDTO.succData(nepuTopicDAO.save(nepuTopic));
//    }

//    public ResponseDTO<List<NepuTopic>> getAll() {
//        return ResponseDTO.succData(nepuTopicDAO.findAll());
//    }
//
//    public ResponseDTO save(NepuTopic nepuTopic) {
//        return ResponseDTO.succData(nepuTopicDAO.save(nepuTopic));
//    }

//    @Override
//    public ResponseDTO<NepuTopic> saveOne(NepuTopicAddDTO nepuTopicAddDTO) {
//        NepuTopic nepuTopic = new NepuTopic();
//        String dictId = nepuTopicAddDTO.getTopicDictId();
//
//        BeanUtil.copyProperties(nepuTopicAddDTO,nepuTopic, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//        Optional<NepuTopicDict> dictOp = dictService.getById(dictId);
//        if (!dictOp.isPresent()){
//            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"词典ID["+dictId+"]对应资源不存在");
//        }
//        NepuTopicDict dict = dictOp.get();
//        nepuTopic.setWorkload(dict.getWorkloadMax());
//        return ResponseDTO.succData(nepuTopicDAO.save(nepuTopic));
//    }
//
//    @Override
//    public ResponseDTO<NepuTopic> updateOne(NepuTopicUpdateDTO nepuTopicUpdateDTO) {
//
//        Optional<NepuTopic> nepuTopicOp = getById(nepuTopicUpdateDTO.getId());
//        if(!nepuTopicOp.isPresent())
//            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"ID:["+
//                    nepuTopicUpdateDTO.getId()+"]对应的纵向课题不存在");
//        NepuTopic nepuTopic = nepuTopicOp.get();
//        BeanUtil.copyProperties(nepuTopicUpdateDTO,nepuTopic,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//        return ResponseDTO.succData(nepuTopicDAO.save(nepuTopic));
//    }

    //    @Override
//    public ResponseDTO<List<NepuTopic>> getAll() {
//        return ResponseDTO.succData(nepuTopicDAO.findAll());
//    }
//
//    @Override
//    public ResponseDTO deleteById(String id) {
//        Optional<NepuTopic> optional = nepuTopicDAO.findById(id);
//        if(!optional.isPresent())
//            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"ID:["+id+"]对应数据不存在");
//        nepuTopicDAO.deleteById(id);
//        return ResponseDTO.succMsg("删除成功");
//    }
//
//    @Override
//    public ResponseDTO save(NepuTopic nepuTopic) {
//        return ResponseDTO.succData(nepuTopicDAO.save(nepuTopic));
//    }
//
//    @Override
//    public ResponseDTO apply(String id) {
//        Optional<NepuTopic> nepuTopic = nepuTopicDAO.findById(id);
//        //已提交
//        nepuTopic.get().setApplyStatus(ApplyStatus.APPLY_SUBMIT);
//        //更新状态
//        nepuTopicDAO.save(nepuTopic.get());
//        NepuTopicAudit nepuTopicAudit = new NepuTopicAudit();
//        nepuTopicAudit.setApplicant(nepuTopic.get().getApplicant());
//        nepuTopicAudit.setTopicId(nepuTopic.get().getId());
//        nepuTopicAudit.setAuditStatus(AuditStatus.AUDIT_NONE);
//        nepuTopicAuditDAO.save(nepuTopicAudit);
//        return ResponseDTO.succMsg("申请成功");
//    }
}
